<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */

namespace app\result;

use app\model\UploadFilesLog;

class UeditorResult
{


    public $sourceDomain = '';//拼接的域名，可选
    public $isSpliceDomain = true;//是否拼接域名
    public $rootPath = '';//绝对路径，可用于删除本地文件

    public $fileField; //文件域名
    private $file; //文件上传对象
    private $base64; //文件上传对象
    public $config; //配置信息
    private $oriName; //原始文件名
    private $fileName; //新文件名
    private $fullName; //完整文件名,即从当前配置目录开始的URL
    private $filePath; //完整文件名,即从当前配置目录开始的URL
    private $fileSize; //文件大小
    private $fileType; //文件类型
    private $stateInfo; //上传状态信息,
    private $stateMap = [ //上传状态映射表，国际化用户需考虑此处数据的国际化
        "SUCCESS", //上传成功标记，在UEditor中内不可改变，否则flash判断会出错
        "文件大小超出 upload_max_filesize 限制",
        "文件大小超出 MAX_FILE_SIZE 限制",
        "文件未被完整上传",
        "没有文件被上传",
        "上传文件为空",
        "ERROR_TMP_FILE" => "临时文件错误",
        "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
        "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
        "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
        "ERROR_CREATE_DIR" => "目录创建失败",
        "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
        "ERROR_FILE_MOVE" => "文件保存时出错",
        "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
        "ERROR_WRITE_CONTENT" => "写入文件内容错误",
        "ERROR_UNKNOWN" => "未知错误",
        "ERROR_DEAD_LINK" => "链接不可用",
        "ERROR_HTTP_LINK" => "链接不是http链接",
        "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确"
    ];

    //配置
    private string $type;


    //入口
    public function ueditor($args = [])
    {
        header("Content-Type: text/html; charset=utf-8");

        if (empty($args['action'])) {
            return [
                'state' => '非法请求，参数不合法'
            ];
        }
        $action = $args['action'];
        $this->get_config();//初始化配置
        switch ($action) {
            case 'config':
                $result = $this->config;
                break;

            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->action_upload($action)->run()->getFileInfo();
                break;

            /* 列出图片 、文件*/
            case 'listimage':
            case 'listfile':
                $result = $this->action_list($action);
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->action_crawler();
                break;

            default:
                $result = [
                    'state' => '请求地址出错'
                ];
                break;
        }

        /* 输出结果 */
        if (isset($args["callback"])) {
            if (preg_match("/^[\w_]+$/", $args["callback"])) {
                echo htmlspecialchars($args["callback"]) . '(' . json_encode($result, JSON_UNESCAPED_UNICODE) . ')';
                exit();
            } else {
                return [
                    'state' => 'callback参数不合法'
                ];
            }
        } else {
            return $result;
        }
    }

    public function get_config()
    {
        $basePath = config('upload.upload_url');
        $this->sourceDomain = config('upload.domain');
        $this->config = [
            'imageActionName' => 'uploadimage',
            'imageFieldName' => 'upfile',
            'imageMaxSize' => 2048000,
            'imageAllowFiles' => [0 => '.png', 1 => '.jpg', 2 => '.jpeg', 3 => '.gif', 4 => '.bmp',],
            'imageCompressEnable' => true,
            'imageCompressBorder' => 1600,
            'imageInsertAlign' => 'none',
            'imageUrlPrefix' => '',
            'imagePathFormat' => $basePath . '/images/{yyyy}{mm}{dd}/{time}{rand:6}',
            'scrawlActionName' => 'uploadscrawl',
            'scrawlFieldName' => 'upfile',
            'scrawlPathFormat' => $basePath . '/images/{yyyy}{mm}{dd}/{time}{rand:6}',
            'scrawlMaxSize' => 2048000,
            'scrawlUrlPrefix' => '',
            'scrawlInsertAlign' => 'none',
            'snapscreenActionName' => 'uploadimage',
            'snapscreenPathFormat' => $basePath . '/images/{yyyy}{mm}{dd}/{time}{rand:6}',
            'snapscreenUrlPrefix' => '',
            'snapscreenInsertAlign' => 'none',
            'catcherLocalDomain' => ['127.0.0.1', 'localhost', 'img.baidu.com', 'jz.test.top', 'jz.api.alipay168.cn'],
            'catcherActionName' => 'catchimage',
            'catcherFieldName' => 'source',
            'catcherPathFormat' => $basePath . '/images/{yyyy}{mm}{dd}/{time}{rand:6}',
            'catcherUrlPrefix' => '',
            'catcherMaxSize' => 2048000,
            'catcherAllowFiles' => [0 => '.png', 1 => '.jpg', 2 => '.jpeg', 3 => '.gif', 4 => '.bmp',],
            'videoActionName' => 'uploadvideo',
            'videoFieldName' => 'upfile',
            'videoPathFormat' => $basePath . '/video/{yyyy}{mm}{dd}/{time}{rand:6}',
            'videoUrlPrefix' => '',
            'videoMaxSize' => 102400000,
            'videoAllowFiles' => [0 => '.flv', 1 => '.swf', 2 => '.mkv', 3 => '.avi', 4 => '.rm', 5 => '.rmvb', 6 => '.mpeg', 7 => '.mpg', 8 => '.ogg', 9 => '.ogv', 10 => '.mov', 11 => '.wmv', 12 => '.mp4', 13 => '.webm', 14 => '.mp3', 15 => '.wav', 16 => '.mid',],
            'fileActionName' => 'uploadfile',
            'fileFieldName' => 'upfile',
            'filePathFormat' => $basePath . '/files/{yyyy}{mm}{dd}/{time}{rand:6}',
            'fileUrlPrefix' => '',
            'fileMaxSize' => 51200000,
            'fileAllowFiles' =>
                [
                    0 => '.png', 1 => '.jpg', 2 => '.jpeg', 3 => '.gif', 4 => '.bmp', 5 => '.flv', 6 => '.swf', 7 => '.mkv', 8 => '.avi', 9 => '.rm', 10 => '.rmvb', 11 => '.mpeg', 12 => '.mpg',
                    13 => '.ogg', 14 => '.ogv', 15 => '.mov', 16 => '.wmv', 17 => '.mp4', 18 => '.webm', 19 => '.mp3', 20 => '.wav', 21 => '.mid', 22 => '.rar', 23 => '.zip', 24 => '.tar', 25 => '.gz', 26 => '.7z', 27 => '.bz2', 28 => '.cab',
                    29 => '.iso', 30 => '.doc', 31 => '.docx', 32 => '.xls', 33 => '.xlsx', 34 => '.ppt', 35 => '.pptx', 36 => '.pdf', 37 => '.txt', 38 => '.md', 39 => '.xml',
                ],
            'imageManagerActionName' => 'listimage',
            'imageManagerListPath' => $basePath . '/images/',
            'imageManagerListSize' => 20,
            'imageManagerUrlPrefix' => '',
            'imageManagerInsertAlign' => 'none',
            'imageManagerAllowFiles' => [0 => '.png', 1 => '.jpg', 2 => '.jpeg', 3 => '.gif', 4 => '.bmp',],
            'fileManagerActionName' => 'listfile',
            'fileManagerListPath' => $basePath . '/files/',
            'fileManagerUrlPrefix' => '',
            'fileManagerListSize' => 20,
            'fileManagerAllowFiles' =>
                [
                    0 => '.png', 1 => '.jpg', 2 => '.jpeg', 3 => '.gif', 4 => '.bmp', 5 => '.flv', 6 => '.swf', 7 => '.mkv', 8 => '.avi', 9 => '.rm', 10 => '.rmvb', 11 => '.mpeg', 12 => '.mpg', 13 => '.ogg', 14 => '.ogv', 15 => '.mov',
                    16 => '.wmv', 17 => '.mp4', 18 => '.webm', 19 => '.mp3', 20 => '.wav', 21 => '.mid', 22 => '.rar', 23 => '.zip', 24 => '.tar', 25 => '.gz', 26 => '.7z', 27 => '.bz2', 28 => '.cab', 29 => '.iso', 30 => '.doc',
                    31 => '.docx', 32 => '.xls', 33 => '.xlsx', 34 => '.ppt', 35 => '.pptx', 36 => '.pdf', 37 => '.txt', 38 => '.md', 39 => '.xml',
                ],
        ];
        return $this->config;
    }


    /**
     * 干活
     * @param string $fileField 表单名称
     * @param string $type 是否解析base64编码，可省略。若开启，则$fileField代表的是base64编码的字符串表单名
     * @return $this
     */
    private function run($fileField = '', $type = "upload")
    {
        if ($fileField) {
            $this->fileField = $fileField;
        }
        $this->type = $type;
        if ($type == "remote") {
            $this->saveRemote();
        } else if ($type == "base64") {
            $this->upBase64();
        } else {
            $this->upFile();
        }

        //这里会报错，屏蔽就可以了
        /*$this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'UTF-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);*/
        return $this;
    }

    /**
     * 上传文件的主处理方法
     * @return mixed
     */
    private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }


        $config = UploadResult::_getConfig();
        $logModel = new UploadFilesLog();
        $md5 = md5_file($file['tmp_name']);
        $has = $logModel->data_get(['md5' => $md5]);
        if ($has) {


            $this->oriName = $has['name'];
            $this->fileSize = $has['size'];
            $this->fileType = $this->getFileExt();
            $this->fullName = $has['path'];
            $this->filePath = $config['root_path'] . $has['path'];


            $this->stateInfo = $this->stateMap[0];
            return $this;
        }
        $type = $config['type'];
        //移动文件
        if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
            $logData = [
                'name' => $this->oriName,
                'size' => $this->fileSize,
                'type' => ltrim($this->fileType, '.'),
                'upload_type' => $type,
                'path' => $this->fullName,
                'user_type' => 1,
                'user_id' => 0,
                'md5' => $md5,
            ];
            $fullUrl = request()->domain() . $logData['path'];
            // 记录日志
            $logData['full_url'] = $fullUrl;

            if ($type == 'qiniu') {
                $qiniu = (new UploadResult())->local2qiniu($this->filePath, $md5 . $this->fileType);
                if ($qiniu['code'] == 0) {
                    $qiniuData = $qiniu['data'];
                    $logData['path'] = $qiniuData['path'];
                    $logData['full_url'] = $qiniuData['full_url'];
                    @unlink($this->filePath);
                    $this->isSpliceDomain = false;
                    $this->fullName = $qiniuData['full_url'];
                }
            }
            $logModel->save($logData);
        }
        return $this;
    }

    /**
     * 处理base64编码的图片上传
     * @return mixed
     */
    private function upBase64()
    {
        $base64Data = $_POST[$this->fileField];
        $img = base64_decode($base64Data);

        $this->oriName = $this->config['oriName'];
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移动文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
        }
        return $this;
    }

    /**
     * 拉取远程图片
     * @return mixed
     */
    private function saveRemote()
    {
        $imgUrl = htmlspecialchars($this->fileField);
        $imgUrl = str_replace("&amp;", "&", $imgUrl);

        //http开头验证
        if (strpos($imgUrl, "http") !== 0) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
            return;
        }
        //获取请求头并检测死链
        $heads = get_headers($imgUrl);
        if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
            $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
            return;
        }

        //格式验证(扩展名验证和Content-Type验证)
        $fileType = strtolower(strrchr($imgUrl, '.'));
        if (!in_array($fileType, $this->config['allowFiles'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
            return;
        }
        //判断类型是否符合要求
        $ok = false;
        foreach ($heads as $v) {
            if (stristr($v, "image")) {
                $ok = true;
            }
        }
        if (!$ok) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
        }


        //打开输出缓冲区并获取远程图片
        ob_start();
        $context = stream_context_create(
            ['http' => [
                'follow_location' => false // don't follow redirects
            ]]
        );
        readfile($imgUrl, false, $context);
        $img = ob_get_contents();
        ob_end_clean();
        preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);

        $this->oriName = $m ? $m[1] : "";
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
        }
        return $this;
    }

    /**
     * 上传错误检查
     * @param $errCode
     * @return string
     */
    private function getStateInfo($errCode)
    {
        return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
    }

    /**
     * 获取文件扩展名
     * @return string
     */
    private function getFileExt()
    {
        return strtolower(strrchr($this->oriName, '.'));
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getFullName()
    {
        //替换日期事件
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        //过滤文件名的非法自负,并替换文件名
        $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        //替换随机字符串
        $randNum = rand(1, 10000000000) . rand(1, 10000000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt();
        return $format . $ext;
    }

    /**
     * 获取文件名
     * @return string
     */
    private function getFileName()
    {
        return substr($this->filePath, strrpos($this->filePath, '/') + 1);
    }

    /**
     * 获取文件完整路径
     * @return string
     */
    private function getFilePath()
    {
        $fullname = $this->fullName;
        $rootPath = $_SERVER['DOCUMENT_ROOT'];

        if (substr($fullname, 0, 1) != '/') {
            $fullname = '/' . $fullname;
        }

        return $rootPath . $fullname;
    }

    /**
     * 文件类型检测
     * @return bool
     */
    private function checkType()
    {
        return in_array($this->getFileExt(), $this->config["allowFiles"]);
    }

    /**
     * 文件大小检测
     * @return bool
     */
    private function checkSize()
    {
        return $this->fileSize <= ($this->config["maxSize"]);
    }

    /**
     * 获取当前上传成功文件的各项信息
     * @return array
     * todo 这里添加七牛、阿里云等配置上传即可
     */
    public function getFileInfo()
    {
        return [
            "state" => $this->stateInfo,
            "url" => $this->isSpliceDomain ? ($this->sourceDomain . $this->fullName) : $this->fullName,
            "title" => $this->fileName,
            "original" => $this->oriName,
            "type" => $this->fileType,
            "size" => $this->fileSize
        ];
    }


    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getfiles($path, $allowFiles, &$files = [])
    {
        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    self:: getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = [
                            'url' => substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime' => filemtime($path2)
                        ];
                    }
                }
            }
        }
        return $files;
    }

    //获取已上传的文件列表
    function action_list($action)
    {

        /* 判断类型 */
        switch ($action) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $this->config['fileManagerAllowFiles'];
                $listSize = $this->config['fileManagerListSize'];
                $path = $this->config['fileManagerListPath'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $this->config['imageManagerAllowFiles'];
                $listSize = $this->config['imageManagerListSize'];
                $path = $this->config['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "" : "/") . $path;
        $files = self::getfiles($path, $allowFiles);
        if (!count($files)) {
            return [
                "state" => "no match file",
                "list" => [],
                "start" => $start,
                "total" => count($files)
            ];
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }
        //倒序
        //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
        //    $list[] = $files[$i];
        //}

        foreach ($list as &$v) {
            $v['url'] = $this->isSpliceDomain ? ($this->sourceDomain . $v['url']) : $v['url'];
        }
        unset($v);

        /* 返回数据 */
        $result = [
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ];

        return $result;
    }

    //抓取远程图片
    function action_crawler()
    {
        set_time_limit(0);
        /* 上传配置 */
        $config = [
            "pathFormat" => $this->config['catcherPathFormat'],
            "maxSize" => $this->config['catcherMaxSize'],
            "allowFiles" => $this->config['catcherAllowFiles'],
            "oriName" => "remote.png"
        ];
        $fieldName = $this->config['catcherFieldName'];
        $this->config = $config;
        /* 抓取远程图片 */
        $list = [];
        if (isset($_POST[$fieldName])) {
            $source = $_POST[$fieldName];
        } else {
            $source = $_GET[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $this->fileField = $imgUrl;
            $this->type = 'remote';
            $info = $this->run($imgUrl, "remote")->getFileInfo();

            array_push($list, [
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ]);
        }

        /* 返回抓取数据 */
        return [
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'list' => $list
        ];
    }

    //上传附件和上传视频
    function action_upload($action)
    {
        /* 上传配置 */
        $base64 = "upload";
        switch (htmlspecialchars($action)) {
            case 'uploadimage':
                $config = [
                    "pathFormat" => $this->config['imagePathFormat'],
                    "maxSize" => $this->config['imageMaxSize'],
                    "allowFiles" => $this->config['imageAllowFiles']
                ];

                $fieldName = $this->config['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config = [
                    "pathFormat" => $this->config['scrawlPathFormat'],
                    "maxSize" => $this->config['scrawlMaxSize'],
                    "allowFiles" => $this->config['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                ];
                $fieldName = $this->config['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $config = [
                    "pathFormat" => $this->config['videoPathFormat'],
                    "maxSize" => $this->config['videoMaxSize'],
                    "allowFiles" => $this->config['videoAllowFiles']
                ];
                $fieldName = $this->config['videoFieldName'];
                break;
            case 'uploadfile':
            default:
            $config = [
                "pathFormat" => $this->config['filePathFormat'],
                "maxSize" => $this->config['fileMaxSize'],
                "allowFiles" => $this->config['fileAllowFiles']
            ];
            $fieldName = $this->config['fileFieldName'];
                break;
        }

        /* 生成上传实例对象并完成上传 */
        $this->config = $config;
        $this->fileField = $fieldName;
        $this->type = $base64;

        return $this;

    }


}
